<?php

namespace app\exception;

use app\ErrorCode;
use think\exception\Handle;
use think\exception\ValidateException;
use think\Response;
use Throwable;

class BaseExceptionHandler extends Handle
{
    public function render($request, Throwable $e) :Response
    {
        // 如果是API异常
        if ($e instanceof ApiException) {
            return json([
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ]);
        }

        if ($e instanceof ValidateException) {
            return json([
                'message' => $e->getMessage(),
                'code' => ErrorCode::VALIDATE_ERROR,
            ]);
        }

        if ($e instanceof \Exception) {
            return json([
                'message' => $e->getMessage(),
                'code' => ErrorCode::SERVER_ERROR,
            ]);
        }

        // 其他异常交给父类处理
        return parent::render($request, $e);
    }
}